Creating Tables at run-time


Tables always created at design time using Database Desktop which exists in Tools
menu. Database Desktop provides easy and visual way to design common database tables
such as Paradox , DBase, and Foxpro tables. When you want to deploy your applications
you need a clear copy of tables (empty tables ) these tables hold only fields structre,
indexes, validity checks and other table properties. After installing your database
application in target computer; empty tables will be copied and every thing will
goes well. Some times you need to create tables at run-time, without using Database
Desktop application, how you can do that?

Creating tables at run-time is a very simple task. Suppose that you want to create
a Telephone table (Phone.db) at run time which contains:
ID, Name, Number, Address,
and
Notes fields. ID is the primary key and there is a secondary index of Name field
called
NameIndex. simply you can write procedure like below:

procedure CreatePhoneTable;
var
 
NewTable: TTable;
begin
NewTable := TTable.Create(nil); // Create table object
 with  NewTable  do
begin
  TableName :=
'C:\Data\Phone.db';
  TableType :=
ttDefault; // Paradox
   FieldDefs.Clear;

   (*** Create fields  ***)
   FieldDefs.Add('ID', ftAutoInc, 0, False);
  FieldDefs.Add(
'Name', ftString, 30, True);
  FieldDefs.Add(
'Number', ftString, 15, True);
  FieldDefs.Add(
'Address', ftString, 40, False);
  FieldDefs.Add(
'Notes', ftMemo, 200, False);

   (*** Create primary key ***)
   IndexDefs.Clear;
  IndexDefs.Add(
'', 'ID', [ixPrimary, ixUnique]);

 
(*** Create Secondary index ***)
   IndexDefs.Add('NameIndex', 'Name', [ixCaseInsensitive]);

   (*** Create physical table ***)
   CreateTable;
 
       (*** Free NewTable object ***)
   Free;


end ;
// With NewTable


end ;

Notes:

- Inorder to run this procedure you must include Db and  DBTables units in unit
clause.

- If table already exists it will be overwritten.

- You do not need to drop any data access components at design time to create tables
at run time.

See also:

Creating components at run-time